<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />





  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/0f81ff2f.js","daovoice")
  daovoice('init', {
      app_id: "6d134c3b"
    });
  daovoice('update');
  </script>




















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.4.1" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.4.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.4.1">


  <link rel="mask-icon" href="/images/logo.svg?v=6.4.1" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.4.1',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="消息队列（Message Queue）简称MQ，用于应用程序之间的消息传递，在消息中间件领域有着广泛的应用。高级消息队列协议（Advenced Message Queuing Protocol）简称（AMQP），是应用层协议的一个开放标准。AMQP协议可以使用任何编程语言实现，基于AMQP协议实现的中间件有：RabbitMQ、ActiveMQ、RocketMQ等。">
<meta name="keywords" content="蓝士钦">
<meta property="og:type" content="article">
<meta property="og:title" content="消息队列知识点梳理">
<meta property="og:url" content="https://www.lanshiqin.com/cb6b0010/index.html">
<meta property="og:site_name" content="蓝士钦">
<meta property="og:description" content="消息队列（Message Queue）简称MQ，用于应用程序之间的消息传递，在消息中间件领域有着广泛的应用。高级消息队列协议（Advenced Message Queuing Protocol）简称（AMQP），是应用层协议的一个开放标准。AMQP协议可以使用任何编程语言实现，基于AMQP协议实现的中间件有：RabbitMQ、ActiveMQ、RocketMQ等。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="https://www.lanshiqin.com/cb6b0010/mq01.png">
<meta property="og:image" content="https://www.lanshiqin.com/cb6b0010/mq02.png">
<meta property="og:image" content="https://www.lanshiqin.com/cb6b0010/mq03.png">
<meta property="og:image" content="https://www.lanshiqin.com/cb6b0010/mq04.png">
<meta property="og:updated_time" content="2019-03-05T12:51:38.459Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="消息队列知识点梳理">
<meta name="twitter:description" content="消息队列（Message Queue）简称MQ，用于应用程序之间的消息传递，在消息中间件领域有着广泛的应用。高级消息队列协议（Advenced Message Queuing Protocol）简称（AMQP），是应用层协议的一个开放标准。AMQP协议可以使用任何编程语言实现，基于AMQP协议实现的中间件有：RabbitMQ、ActiveMQ、RocketMQ等。">
<meta name="twitter:image" content="https://www.lanshiqin.com/cb6b0010/mq01.png">



  <link rel="alternate" href="/atom.xml" title="蓝士钦" type="application/atom+xml" />




  <link rel="canonical" href="https://www.lanshiqin.com/cb6b0010/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>消息队列知识点梳理 | 蓝士钦</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

  <script src="/js/src/photoswipe.js?v="></script>
  <script src="/js/src/photoswipe-ui-default.js?v="></script>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蓝士钦</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">编程是一种信仰</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-相册">
    <a href="/photos/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-photo"></i> <br />相册</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.lanshiqin.com/cb6b0010/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="蓝士钦">
      <meta itemprop="description" content="编程是一种信仰">
      <meta itemprop="image" content="/images/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蓝士钦">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">消息队列知识点梳理
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-03 11:19:57" itemprop="dateCreated datePublished" datetime="2019-03-03T11:19:57+08:00">2019-03-03</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-03-05 20:51:38" itemprop="dateModified" datetime="2019-03-05T20:51:38+08:00">2019-03-05</time>
              
            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>消息队列（Message Queue）简称MQ，用于应用程序之间的消息传递，在消息中间件领域有着广泛的应用。高级消息队列协议（Advenced Message Queuing Protocol）简称（AMQP），是应用层协议的一个开放标准。AMQP协议可以使用任何编程语言实现，基于AMQP协议实现的中间件有：RabbitMQ、ActiveMQ、RocketMQ等。<br><a id="more"></a></p>
<h1 id="基础部分"><a href="#基础部分" class="headerlink" title="基础部分"></a>基础部分</h1><h2 id="使用消息队列的优点"><a href="#使用消息队列的优点" class="headerlink" title="使用消息队列的优点"></a>使用消息队列的优点</h2><p>使用消息队列之前，可以先看看消息队列有什么优点，能够解决什么样的问题，也就是为什么要使用消息队列的原因</p>
<h3 id="解耦"><a href="#解耦" class="headerlink" title="解耦"></a>解耦</h3><p><code>使用消息队列前</code><br><img src="/cb6b0010/mq01.png" title="mq"><br>系统A直接调用系统B、系统C，调用代码是硬编码的，系统之间存在依赖耦合的关系。<br>如果后续有新的系统需要接入到A系统中，那么就需要通过不断的修改A系统的代码来实现，不利于系统扩展。</p>
<p><code>使用消息队列后</code><br><img src="/cb6b0010/mq02.png" title="mq"><br>系统A不直接调用其他系统，而是将消息发送给消息队列，系统A不必关心有多少个系统会消费该消息。后续有新系统需要接入时，只需要订阅消息队列即可。</p>
<h3 id="异步"><a href="#异步" class="headerlink" title="异步"></a>异步</h3><p><code>使用消息队列前</code><br><img src="/cb6b0010/mq03.png" title="mq"><br>系统A调用一个核心业务很快就完成了，但是后续还需要等待非核心业务完成后才通知用户执行成功，这样等待时间太久了用户会不耐烦。</p>
<p><code>使用消息队列后</code><br><img src="/cb6b0010/mq04.png" title="mq"><br>系统A在1ms内完成核心业务的调用并通知用户执行成功，整个过程用户只等待了1ms，很大程度的提高了用户体验。<br>核心业务成功发送消息到MQ就算业务执行完成了，不必关心后面的非核心业务是否已经消费消息。<br>在高并发的场景下也经常会使用到这种异步方式，可以对流量进行消峰，将非核心业务放到消息队列中滞后处理，等待资源空闲时从队列中取出消息逐个处理。</p>
<h2 id="使用消息队列的缺点"><a href="#使用消息队列的缺点" class="headerlink" title="使用消息队列的缺点"></a>使用消息队列的缺点</h2><p>使用消息队列的优点同样也产生了相应的缺点，要足够了解所可能带来到风险并且根据实际业务场景合理规避风险。</p>
<h3 id="解耦影响系统可用性"><a href="#解耦影响系统可用性" class="headerlink" title="解耦影响系统可用性"></a>解耦影响系统可用性</h3><p>引入了消息队列之后，由于各个系统之间采用消息队列进行通信，如果消息队列停止运行了，那么相当于整个架构体系内的系统都变成了不可用。</p>
<h3 id="异步增加系统复杂性"><a href="#异步增加系统复杂性" class="headerlink" title="异步增加系统复杂性"></a>异步增加系统复杂性</h3><p>由于网络故障等原因，消费者在消费完成后没有发送确认消息给消息队列，消息队列认为消息没有送达而重复发送消息，导致订阅者收到多次相同到消息重复消费，这时就需要消费者自己处理重复消息。<br>由于网络故障或者其他不可抗拒的外部因素，如何保证可靠性传输也是要解决的一个问题，主要体现在以下4个方面：<br>防止重复消费的问题、防止生产者丢数据、防止消息队列丢数据、防止消费者丢数据。</p>
<h2 id="针对消息队列的缺点如何进行完善"><a href="#针对消息队列的缺点如何进行完善" class="headerlink" title="针对消息队列的缺点如何进行完善"></a>针对消息队列的缺点如何进行完善</h2><h3 id="如何保证高可用"><a href="#如何保证高可用" class="headerlink" title="如何保证高可用"></a>如何保证高可用</h3><p>一般在生产环境中都会采用消息队列集群和主从模式来保证高可用，文章后半部分都以RabbitMQ的实现方式为例。</p>
<h3 id="如何防止重复消费的问题"><a href="#如何防止重复消费的问题" class="headerlink" title="如何防止重复消费的问题"></a>如何防止重复消费的问题</h3><p>解决这个问题之前先考虑一下，为什么会收到重复消息？<br>这里以RabbitMQ为例，正常情况下，消费者在消费完消息之后都会给消息队列发送一个确认信息，消息队列收到该确认信息后会将该消息删除，因为网络故障等原因，消息队列没有收到消费者的确认信息，导致消息队列继续存在该消息，并且下次会重复被消费。<br>解决的方式可以根据实际业务场景来决定：</p>
<ol>
<li>业务系统接收到消息之后一般会有入库操作，将消息的id作为记录主键，一旦收到重复消息就会抛出主键插入异常。</li>
<li>业务系统将消息处理结果存储到redis中，同样使用消息的id作为key，即使收到同样的消息set了多次也只会有一条消息，因为消息id一样，所以无论设置多少次都会保证幂等性。</li>
<li>采用redis的key-value方式做一个消费记录，消费者收到消息后先拿消息id去消费记录里查找，如果查找到了说明已经被消费过了就不处理相关业务，如果消息记录里没有该消息的id，则将该消息set到redis记录中，并进行相关业务处理。<h3 id="如何保证传输的可靠性"><a href="#如何保证传输的可靠性" class="headerlink" title="如何保证传输的可靠性"></a>如何保证传输的可靠性</h3>要保证传输可靠性，就要考虑到整个消息队列前后有可能发生到问题并进行处理。<h4 id="防止生产者丢消息"><a href="#防止生产者丢消息" class="headerlink" title="防止生产者丢消息"></a>防止生产者丢消息</h4>生产者将消息发送到消息队列到过程中，由于网络故障等因素导致消息队列无法接受到消息。<br>RabbitMQ提供了两种解决方案：</li>
</ol>
<ul>
<li>transaction<br>transaction模式采用事务的方式保证生产者消息成功送达到消息队列。发消息前先开启事务，然后再发送消息，发送的过程中如果异常就执行回滚，成功就提交事务。</li>
<li>confirm<br>采用transaction模式的缺点是每次发送消息前都要先开启事务，这种操作理论上会降低消息队列的吞吐量。<br>confirm模式相比transaction模式有着更高的吞吐量，一旦生产者将消息投递到所有匹配到消息队列之后，RabbitMQ就会发送一个ACK给生产者，使生产者知道消息已经正确到达目的队列了。如果没有送达消息队列，消息队列会发送一个Nack消息给生产者，生产者接收到该消息后可以决定是否进行重发。<h4 id="防止消息队列丢消息"><a href="#防止消息队列丢消息" class="headerlink" title="防止消息队列丢消息"></a>防止消息队列丢消息</h4>开启持久化磁盘，并配合Confirm，消息持久化到磁盘后再给生产者发一个ACK信号，如果持久化磁盘之前MQ就停止运行了，生产者收不到ACK信号会自动进行重发。MQ如果一直停止运行，生产者根据业务场景进行多次重试仍然发送失败，生产者应该实现报警并记录日志。<h4 id="防止消费者丢消息"><a href="#防止消费者丢消息" class="headerlink" title="防止消费者丢消息"></a>防止消费者丢消息</h4>消费者收到消息队列的消息后会自动发送一个ACK确认消息给消息队列。在接收到消息并发送确认收到信息后，由于消费者自身的业务异常导致消息没有被合理的处理，导致消息丢失。可以根据实际的业务场景，将自动发送确认消息改为手动发送，在消费者业务代码正常执行完成之后再手动确认消息。</li>
</ul>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2fb233e2/index.html" rel="next" title="使用Python实现一个按键精灵">
                <i class="fa fa-chevron-left"></i> 使用Python实现一个按键精灵
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/f9e910b8/index.html" rel="prev" title="RabbitMQ知识点梳理">
                RabbitMQ知识点梳理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div id="gitalk-container"></div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.png"
                alt="蓝士钦" />
            
              <p class="site-author-name" itemprop="name">蓝士钦</p>
              <p class="site-description motion-element" itemprop="description">编程是一种信仰</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">7</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/lanshiqin" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/l18120788756" target="_blank" title="Weibo"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.jianshu.com/u/082f73dac819" target="_blank" title="JianShu"><i class="fa fa-fw fa-heartbeat"></i>JianShu</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:lanshiqin@outlook.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基础部分"><span class="nav-number">1.</span> <span class="nav-text">基础部分</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用消息队列的优点"><span class="nav-number">1.1.</span> <span class="nav-text">使用消息队列的优点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解耦"><span class="nav-number">1.1.1.</span> <span class="nav-text">解耦</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异步"><span class="nav-number">1.1.2.</span> <span class="nav-text">异步</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用消息队列的缺点"><span class="nav-number">1.2.</span> <span class="nav-text">使用消息队列的缺点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解耦影响系统可用性"><span class="nav-number">1.2.1.</span> <span class="nav-text">解耦影响系统可用性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#异步增加系统复杂性"><span class="nav-number">1.2.2.</span> <span class="nav-text">异步增加系统复杂性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#针对消息队列的缺点如何进行完善"><span class="nav-number">1.3.</span> <span class="nav-text">针对消息队列的缺点如何进行完善</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#如何保证高可用"><span class="nav-number">1.3.1.</span> <span class="nav-text">如何保证高可用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何防止重复消费的问题"><span class="nav-number">1.3.2.</span> <span class="nav-text">如何防止重复消费的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#如何保证传输的可靠性"><span class="nav-number">1.3.3.</span> <span class="nav-text">如何保证传输的可靠性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#防止生产者丢消息"><span class="nav-number">1.3.3.1.</span> <span class="nav-text">防止生产者丢消息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#防止消息队列丢消息"><span class="nav-number">1.3.3.2.</span> <span class="nav-text">防止消息队列丢消息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#防止消费者丢消息"><span class="nav-number">1.3.3.3.</span> <span class="nav-text">防止消费者丢消息</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">蓝士钦</span>

  

  
</div>










  <div class="footer-custom">闽ICP备15027850号</div>


        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    
	
    

    
  </div>

  

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.4.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.4.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.4.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.4.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.4.1"></script>
<script src="/js/src/photoswipe.js?v="></script>
<script src="/js/src/photoswipe-ui-default.js?v="></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.4.1"></script>



  



  










  <link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css">
  <script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
   <script type="text/javascript">
        var gitalk = new Gitalk({
          clientID: '08543e172f1359fce9c3',
          clientSecret: 'a8dd355f95e5035e0266c695e489fa991c9d28e2',
          repo: 'lanshiqin-blog',
          owner: 'lanshiqin',
          admin: ['lanshiqin'],
          id: location.pathname,
          distractionFreeMode: 'true'
        })
        gitalk.render('gitalk-container')           
       </script>

  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
<!-- 页面点击小红心 --> 
<script type="text/javascript" src="/js/src/love.js"></script>
<!--崩溃欺骗-->
<script type="text/javascript" src="/js/src/crash_cheat.js"></script>